var rootUrl = getRoot();
var EXPORT_MAX_ROWS_NAME = '1万条';
var baseUrl = rootUrl +"/websql";
var tplActionUrl = rootUrl + '/websql/tpl/';
var dbList;

function getDbListValue() {
	return dbList.getValue();
}
function getTableColumnUrl() {
	return getRoot() + '/websql/autoCompleteTableColumns?dataId='+dataBase_id+'&baseType='+base_type+'&dataSourceId='+dataSource_id+'&dataSource='+data_source+'&isLocal='+isLocal;
}
function getAllDbTables() {
	return getRoot() + '/websql/getAllDbTables?dataId='+dataBase_id+'&baseType='+base_type+'&dataSourceId='+dataSource_id+'&dataSource='+data_source+'';
}
function getParamType() {
	return "column_group";
}
  
var resultTabPanel;
var pageSizeArray = [
                     {data:5},
                     {data:10},
                     {data:20},
                     {data:50},
                     {data:100}
                 ];

// Tuning SQL button
var tunningSQLItem;
// Tunning tab panel
var tunningTabPanel;
var g_result_index = 0;
var SQL_TYPE_SELECT = 1;
var SQL_TYPE_SELECT_FOR_UPDATE = 2;
var SQL_TYPE_SHOW = 6;
var SQL_TYPE_EXPLAIN = 11;
var MAX_ROWS = 3000;
var EXPORT_MAX_ROWS = 10000;
var EXPORT_MAX_ROWS_NAME = "1万条";
var parentPanelKey = null;


var initMaxRows = function() {
    if(window.parent) {
        if(window.parent.maxLimitRows) {
            EXPORT_MAX_ROWS = window.parent.maxLimitRows;
            if(MAX_ROWS > EXPORT_MAX_ROWS) {
                MAX_ROWS = EXPORT_MAX_ROWS;
            }
            EXPORT_MAX_ROWS_NAME = window.parent.maxLimitRowsName;
        }
    }
};
initMaxRows();


var isLimitExport = false, isLimitAllExport = false;
var isLimitExportUrl = false ,limitExportUrl = null; 
if(window.parent) {
    if(window.parent.limitExport == "1") {
        isLimitExport = true;
    }
    if(window.parent.limitAllExport == "1") {
        isLimitAllExport = true;
    }
    if(window.parent.limitExportUrl) {
        isLimitExportUrl = true;
        limitExportUrl =  window.parent.limitExportUrl;
        isLimitAllExport = true;
    }
}
function isQuery(sqlType) {
    return (sqlType == SQL_TYPE_SELECT || sqlType == SQL_TYPE_SELECT_FOR_UPDATE || sqlType == SQL_TYPE_SHOW || sqlType == SQL_TYPE_EXPLAIN);
}
/*************common function zc**************/
var lTrimZero = function(value) {
    var index = 0;
    for(; index < value.length ; index++) {
        if(value.charCodeAt(index) != 0) {
            break;
        }
    }
    if(index != 0) {
        return value.substring(index);
    }
    return value;
};
/*************common function begin**************/
Ext.define('ModelSqlPlan', {
    extend:'Ext.data.Model',
    fields:["id", "select_type", "table", "type", "possible_keys", "key", "key_len", "ref", "rows", "extra"]
});
function getSql() {
    var sql = Ext.getCmp("tx_sql").getValue();
    var selectSql = Ext.getCmp("tx_sql").editor.getSelection();
    if (selectSql != '') {
        sql = selectSql;
    }
    return sql;
}
function getFullSqlText() {
   return Ext.getCmp("tx_sql").getValue();
}
function focusInput() {
    var sqlArea = Ext.getCmp('tx_sql');
    sqlArea.editor.focus();
    var endLines = sqlArea.editor.lineCount();
    var lastLength = sqlArea.editor.getLine(endLines - 1).length;
    sqlArea.editor.setCursor(endLines - 1, lastLength);  //光标移到最后
}
function encodeValue(value, meta, record) {
    return '<pre style="padding: 0;margin:0;font-family:新宋体,Lucida Console,monospace">' + Ext.util.Format.htmlEncode(value) + '</pre>';
}
function isNull(value) {
    return (value == null);
}
function isNumberDataType(dataType) {
    return (dataType.indexOf('INT') >= 0 || dataType == 'REAL' || dataType == 'FLOAT' || dataType == 'DOUBLE' || dataType == 'NUMBER' || dataType == 'NUMERIC');
}
function isBitDataType(dataType) {
    return (dataType == 'BIT');
}
function isStringDataType(dataType) {
    return (dataType.indexOf('CHAR') >= 0 || dataType.indexOf('TEXT') >= 0 || dataType == "TIMESTAMP");
}
function getFieldValueStr(value, dataType) {
    if (value == null) {
        return null
    }else if(value == "CURRENT_TIMESTAMP" && dataType == "TIMESTAMP") {
        return value;
    }else if(dataType.indexOf("BINARY") != -1 && value.substring(0 , 2) == '0x') {
        if(value == "0x") {
            return "''";
        }else {
            return value;
        }
    }else if(dataType == 'BINARY') {
        return "'" + lTrimZero(value) + "'";
    }else if (value === '' && !isStringDataType(dataType)) {
        return null;
    } else if (isNumberDataType(dataType)) {
        return value;
    } else if (isBitDataType(dataType)) {
        return 'b\'' + value + '\'';
    } else {
        return "'" + value.replaceAll('\\\\', '\\\\').replaceAll('\'', '\\\'') + "'";
    }
}
/*************common function end**************/

/*****/
function openPostWindow(url, sql, name) {
    var tempForm = document.createElement("form");
    tempForm.id = "tempForm1";
    tempForm.method = "post";
    tempForm.action = '/mysql' + url;
    tempForm.target = name;
    var hideInput = document.createElement("input");
    hideInput.type = "hidden";
    hideInput.name = "sql";
    hideInput.value = sql;
    tempForm.appendChild(hideInput);
    document.body.appendChild(tempForm);
    tempForm.submit();
    document.body.removeChild(tempForm);
}
function getMetaTables(gridInput) {
    var grid = (gridInput);
    var result = new Array(); var map = new SimpleMap();
    var fields = grid.metas;
    if (!fields) {
    	return result;
    }
    for (var i = 0; i < fields.length; i ++) {
        var field = fields[i];
        if (field.name.substr(0, 7) == "COLUMN_") {
            if (field.tableName != '' && field.dbName !='information_schema' && field.dbName !='performance_schema') {
                var key = field.dbName + "$$" + field.tableName;
                if (result.length == 0) {
                    result.push({tableName:field.tableName, dbName:field.dbName});
                    map.put(key);
                } else {
                    for (var j = 0; j < result.length; j ++) {
                        if (!map.contains(key)) {
                            result.push({tableName:field.tableName, dbName:field.dbName});
                            map.put(key);
                        }
                    }
                }
            }
        }
    }
    return result;
}
function exportResult(format,result_index) {
    var postData = {};
    var _gridResult = Ext.getCmp('result_' + result_index);
    var tables = getMetaTables(_gridResult);
    var tableName = 'xxxxxx';
    var dbName = 'xxxxxx';
    if (tables.length > 0) {
        tableName = tables[0].tableName;
        dbName = tables[0].dbName;
    }
    
    var sql = _gridResult.sql;
    var store = _gridResult.store;
    if(store.getTotalCount() > 0) {
        var record = store.getAt(0);
        var data = jsonToString(record.data);
        if(data.length * 1.5 > 10240) {
            return submitNewSQLJob({
                fileType:format,
                fileCharset:'utf8',
                compressInsert:'N',
                enableCsvTitleRow:'Y',
                tableRowsLimit:EXPORT_MAX_ROWS,
                dbName:dbName,
                sql:sql,
                createDesc:'SQL Window导出' + EXPORT_MAX_ROWS_NAME + '由于行长较长自动生成异步任务'
            });
        }
    }
    openPostWindow(baseUrl + 'export.do?format=' + format + '&panelKey=export&tableName=' + tableName + '&dbName=' + _gridResult.dbName + '&rows=' + EXPORT_MAX_ROWS + '&_nocache=' + Math.random() + "&token=" + getUserToken(), sql, "_blank");
}
function exportMoreData(result_index) {
	var _gridResult = Ext.getCmp('result_' + result_index);
    addNewSQLJob(_gridResult.dbName , _gridResult.sql);
}
/*****/

/**********template begin****************/
//new treePanel

Ext.define('User', {
    extend: 'Ext.data.Model',
    fields: [
        {name: 'node', type: 'string'}
    ]
});

var myStore = Ext.create('Ext.data.TreeStore', {
    model: 'User',
    proxy: {
        type: 'ajax',
        data:{node:"root"},
        url: rootUrl + '/dataManage/queryChildrenById',
        reader: {
            type: 'json',
            root: 'users'
        }
    },
    autoLoad: false
});
var childrenArray=new Array();
function getSqlTemp(){
	var url=rootUrl + '/dataManage/getSqlTempList';
	var sql_category;
	if(base_type.toUpperCase() == 'ORACLE'){
		sql_category = 3;
	}else{
		sql_category = 1;
	}
	var param={pid:0,sql_category:sql_category}
	 $.ajax({
		  url: url,
		  async: false,
		  data:param,
		  type:'post',
		  success:getSqlTempList,
		  error: function(XMLHttpRequest, textStatus, errorThrown) {
			  alert(XMLHttpRequest.status);
			  alert(XMLHttpRequest.readyState);
			  alert(textStatus);
			    }
		});
	
}
var getSqlTempList = function(json){
	var list = json.list;
	if(list.length>0){
		childrenArray=sqlTempRecursion(list,true);
	}
	
}
var sqlTempRecursion= function(array,flag){
	var arrayList=new Array();
	for(var i=0;i<array.length;i++){
		var param={};
		param.id=array[i].id;
		param.text=array[i].childrenName;
		if(flag){
			param.expanded=true;
		}
		param.leaf=array[i].leaf==0?false:true;
		param.comment=array[i].leaf==0?"":array[i].comment;
		param.children=sqlTempRecursion(array[i].sqlTplMenuVOs,false);
		arrayList.push(param);
	}
	return arrayList;
}
getSqlTemp();
var store = Ext.create('Ext.data.TreeStore', {
    root: {
        expanded: true,
        children: childrenArray/*[
            { text: "SQL",expanded: true,children: [
                { text: "常用SQL", leaf: false ,expanded: true,children:[
                     {id:"1" , text: "select", leaf: true},
                     {id:"3" , text: "insert", leaf: true},
                     {id:"4" , text: "update", leaf: true},
                     {id:"5" , text: "delete", leaf: true},
                     {id:"6" , text: "replace", leaf: true}
                 ]},
                 { text: "SHOW", leaf: false ,expanded: true,children:[
                                                                        {id:"7" , text: "show character set", leaf: true},
                                                                        {id:"8" , text: "show collation", leaf: true},
                                                                        {id:"9" , text: "show column", leaf: true},
                                                                        {id:"10" , text: "show create database", leaf: true}
                                                                    ]},
                 { text: "表/索引", leaf: false ,expanded: true,children:[
                                      {id:"12" , text: "create index", leaf: true}
                           ]}                                                    
             ] },
             { text: "函数",expanded: true,children: [
                 { text: "字符型", leaf: false ,expanded: true,children:[
                     {id:"2" , text: "ascii", leaf: true},
                     {id:"16" , text: "bin", leaf: true},
                     {id:"17" , text: "bit_length", leaf: true},
                     {id:"18" , text: "char", leaf: true}
                 ]}
             ] }
        ]*/
    }
});

/*var store;
if(abc == 'oracle' || abc == 'drds'){
	store = Ext.create('Ext.data.TreeStore', {
	    root: {
	        expanded: true,
	        children: [
	            { text: "SQL",expanded: true,children: [
	                { text: "常用SQL", leaf: false ,expanded: true,children:[
	                     {id:"1" , text: "select", leaf: true},
	                     {id:"3" , text: "insert", leaf: true},
	                     {id:"4" , text: "update", leaf: true},
	                     {id:"5" , text: "delete", leaf: true},
	                     {id:"6" , text: "replace", leaf: true}
	                 ]},
	                 { text: "SHOW", leaf: false ,expanded: true,children:[
	                                                                        {id:"7" , text: "show character set", leaf: true},
	                                                                        {id:"8" , text: "show collation", leaf: true},
	                                                                        {id:"9" , text: "show column", leaf: true},
	                                                                        {id:"10" , text: "show create database", leaf: true}
	                                                                    ]},
	                 { text: "表/索引", leaf: false ,expanded: true,children:[
	                                     {id:"12" , text: "create index", leaf: true}
	                           ]}                                                    
	             ] },
	             { text: "函数",expanded: true,children: [
	                 { text: "字符型", leaf: false ,expanded: true,children:[
	                     {id:"2" , text: "ascii", leaf: true},
	                     {id:"16" , text: "bin", leaf: true},
	                     {id:"17" , text: "bit_length", leaf: true},
	                     {id:"18" , text: "char", leaf: true}
	                 ]}
	             ] }
	        ]
	    }
	});
}else if(abc == 'mysql'){
	store = Ext.create('Ext.data.TreeStore', {
	    root: {
	        expanded: true,
	        children: [
	            { text: "SQL",expanded: true,children: [
	                { text: "常用SQL", leaf: false ,expanded: true,children:[
	                     {id:"1" , text: "select", leaf: true},
	                     {id:"3" , text: "insert", leaf: true},
	                     {id:"4" , text: "update", leaf: true},
	                     {id:"5" , text: "delete", leaf: true},
	                     {id:"6" , text: "replace", leaf: true}
	                 ]},
	                 { text: "SHOW", leaf: false ,expanded: true,children:[
	                                                                        {id:"7" , text: "show character set", leaf: true},
	                                                                        {id:"8" , text: "show collation", leaf: true},
	                                                                        {id:"9" , text: "show column", leaf: true},
	                                                                        {id:"10" , text: "show create database", leaf: true}
	                                                                    ]},
	                 { text: "表/索引", leaf: false ,expanded: true,children:[
	                                     {id:"12" , text: "create index", leaf: true}
	                           ]}                                                    
	             ] },
	             { text: "函数",expanded: true,children: [
	                 { text: "字符型", leaf: false ,expanded: true,children:[
	                     {id:"2" , text: "ascii", leaf: true},
	                     {id:"16" , text: "bin", leaf: true},
	                     {id:"17" , text: "bit_length", leaf: true},
	                     {id:"18" , text: "char", leaf: true}
	                 ]}
	             ] }
	        ]
	    }
	});
}
*/
Ext.create('Ext.tree.Panel', {
    title: 'Simple Tree',
    width: 200,
    height: 150,
    store: store,
    rootVisible: false,
    renderTo: Ext.getBody()
});


//template store
/*var treeTplStore = new IDB.TreeStore({
	autoLoad:false,
	url:rootUrl + '/dataManage/queryChildrenById'
});
treeTplStore.on('load', function () {
	treeTpl.setLoading(false);
});*/
//template tree panel
var treeTpl = new Ext.tree.Panel({
  store:store,
  loadMask:true,
  rootVisible:false,
  enableDD:true,
  viewConfig:{
      plugins:{
          ptype:'treeviewdragdrop',
          ddGroup:'sqlText',
          enableDrop:false
      }
  },
  listeners:{
      itemdblclick:function (thiz, record) {
          if (record.get('leaf')){
              var id = record.get('id');
              appendTplContentById(id);
          }
      }
  }
});
Ext.define('ModelTplQueryResult', {
  extend:'Ext.data.Model',
  fields:["ID", "NAME", "QTIP"]
});
var storeTplQueryResult = Ext.create('Ext.data.Store', {
  model:'ModelTplQueryResult',
  pageSize:50,
  data:[],
  proxy:{
      type:'ajax',
      url:tplActionUrl + '/queryTplListByName.do',
      reader:{
          type:'json',
          root:'root'
      }
  }
});
var gridTplQueryResult = Ext.create('Ext.grid.Panel', {
  region:'center',
  width:'100%',
  store:storeTplQueryResult,
  border:false,
  loadMask:true,
  columns:[
      {header:'查询结果', width:240, dataIndex:'NAME'}
  ],
  viewConfig:{
      plugins:{
          ptype:'gridviewdragdrop',
          ddGroup:'sqlText',
          enableDrop:false
      }
  },
  listeners:{
      itemdblclick:function () {
          var selected = gridTplQueryResult.getSelectionModel().getSelection()[0];
          if (!selected) {
              Ext.Msg.alert('提示', '请选择记录！');
          } else {
              appendTplContentById(selected.get('ID'));
          }
      }
  }
});

var tabPanelTpl = new Ext.TabPanel({activeTab:0, headerStyle:'display:none',
  tbar:[
      {xtype:'textfield', id:'tx_TplQueryText', width:120, enableKeyEvents:true, listeners:{
          keypress:function (o, event) {
              if (event.keyCode == 13) {
                  queryTpl();
              }
          }
      }},
      {text:'查询', handler:queryTpl}
  ],
  region:'east', width:200, collapsible:true, split:true, title:'模板(双击插入)', tabPosition:'bottom', removePanelHeader:true,
  items:[
      {title:'模板导航', layout:'fit', items:[treeTpl]},
      {title:'搜索结果', layout:'fit', items:[gridTplQueryResult]}
  ]
});
function appendTplContentById(id) {
  Ext.Ajax.request({
      url:rootUrl + '/dataManage/queryTplContentById',
      params:{
          id:id
      },
      success:function (response) {
          var rs = Ext.decode(response.responseText);
          if (rs.success) {
              if (!true) {
                  Ext.MessageBox.alert('提示', '未取到模板内容');
              } else {
                  var sql = Ext.getCmp("tx_sql").getValue();
                  Ext.getCmp("tx_sql").setValue(sql + '\n' + rs.root.comment);
              }
          }
      }
  });
}
function queryTpl() {
  var name = Ext.String.trim(Ext.getCmp('tx_TplQueryText').getValue());
  if (name == '') {
      Ext.Msg.alert('提示', '请输入查询的信息！')
  } else {
      storeTplQueryResult.load({
          params:{
              name:name
          }
      });
      tabPanelTpl.setActiveTab(1);
  }

}
/**********template end****************/



/************user sql begin******************/
var userPreTitle = '';
var deleteUserSQL = function() {
    var selectedRows = userSQLGrid.getSelectionModel().getSelection();
    if(selectedRows && selectedRows.length > 0) {
        var id = selectedRows[0].get('id');
        Ext.Msg.confirm('提示' , '该SQL删除后无法回滚，是否继续？' , function(v) {
            if(v == 'yes') {
                userSQLWindow.getEl().mask('正在删除SQL...');
                ajax({
                    url:rootUrl+'/dataManage/removeUserSql',
                    onlyUrl:true,
                    params:{id:id},
                    success:function(resp) {
                        userSQLWindow.getEl().unmask();
                        var json = jsonDecode(resp.responseText);
                        if(json.success) {
                            userSQLGrid.store.load();
                        }else {
                            Ext.Msg.alert('提示' , json.root);
                        }
                    },
                    failure:function() {
                        userSQLWindow.getEl().unmask();
                    }
                });
            }
        });
    }
};
var editUserSQL = function() {
    var selectedRows = userSQLGrid.getSelectionModel().getSelection();
    if(selectedRows && selectedRows.length > 0) {
        var row = selectedRows[0];
        var id = row.get('id');
        userSQLWindow.getEl().mask('正在加载SQL...');
        ajax({
            url:rootUrl+'/dataManage/getUserSqlInfoById',
            onlyUrl:true,
            params:{id:id},
            success:function(resp) {
                userSQLWindow.getEl().unmask();
                var json = jsonDecode(resp.responseText);
                if(json.success) {
                    saveUserSQL('edit' , function() {
                        userSQLGrid.store.load();
                    },row , json.list[0]);
                }else {
                    Ext.Msg.alert('提示' , json.root);
                }
            },
            failure:function() {userSQLWindow.getEl().unmask()}
        });
    }
};
var userSQLGrid , userSQLWindow;
var manageUserSQL = function() {
    var store = new Ext.data.Store({
        autoLoad:true,
        fields:['id' , 'sqlTitle', 'sqlContent' , 'sqlScope'],
        proxy:{
            type:'ajax',
            url:rootUrl+'/dataManage/showUserSql?datatableName='+objectName+'&databaseId='+dataBase_id+'',
            reader:{
                type:'json',
                root:'list'
            }
        }
    });
    var grid = userSQLGrid = new Ext.grid.Panel({
        emptyText:'你还没有保存过SQL，赶紧增加一个试一试吧！',
        selType:'rowmodel',
        viewConfig:{ stripeRows:true, enableTextSelection:true},
        store:store,
        columns:[
            {xtype: 'rownumberer'},
            {text:"标题",dataIndex:"sqlTitle",  width:120},
            {text:'SQL概要', dataIndex:'sqlContent',width:340,renderer:encodeValue},
           /* {text:'适用范围',dataIndex:'tmp',width:200,renderer:function(v,c,row) {
                var sqlScope = row.get('sqlScope');
                if(sqlScope == 'all') {
                    return '所有库';
                }else if(sqlScope == 'instance') {
                    return '实例：' + row.get('userInstance');
                }else if(sqlScope == 'db') {
                    return '库：' + row.get('dbName') + "（" + row.get('userInstance') + "）";
                }
            }},*/
            {text:'操作',width:80,renderer:function(v,c,row) {
                return '<a href="javascript:editUserSQL()">编辑</a> <a href="javascript:deleteUserSQL()">删除</a>'
            }}
        ],
        listeners:{
            itemdblclick:function(thiz,record) {
                var id = record.get("id");
                userSQLWindow.getEl().mask('正在加载SQL...');
                ajax({
                    url:rootUrl+'/dataManage/showUserSql',
                    onlyUrl:true,
                    params:{databaseId:dataBase_id,datatableName:objectName},
                    success:function(resp) {
                        userSQLWindow.getEl().unmask();
                        var json = jsonDecode(resp.responseText);
                        if(json.success) {
                            addSQLValueForSelection(json.root);
                            win.close();
                        }else {
                            Ext.Msg.alert('提示' , json.root);
                        }
                    },
                    failure:function() {userSQLWindow.getEl().unmask()}
                });
            }
        }
    });
    var win = userSQLWindow = new IDB.Window({
        title:'管理我的SQL',height:400,width:790,
        items:[grid],
        buttons:[{
            text:'新增',handler:function() {
                saveUserSQL('add',function() {
                    grid.store.load();
                });
            }
        },{
            text:'关闭',handler:function() {win.close()}
        }]
    });
};
var saveUserSQL = function(option,fn,editRecord,editSql) {
    var sqlText = getSql();
    // set support user sql option
    var isOnUserSQL = true ;
    if('off' == supportUserSQLS) {
    	isOnUserSQL = false;
    }
    var nowDB = {name:'sqlScope',inputValue:'db',boxLabel:'当前库'};
    var items = [];
    if(isOnUserSQL) {
    	items = [
             {name:'sqlScope',inputValue:'all',boxLabel:'所有库',checked:true},
             {name:'sqlScope',inputValue:'instance',boxLabel:'当前实例'}, 
             nowDB
    	];
    }else {
    	items = [
                 {name:'sqlScope',inputValue:'instance',boxLabel:'当前实例',checked:true}, 
                 nowDB
        	];
    }
    var form = new IDB.FormPanel({
        defaults:{
            bodyPadding:5,
            padding:'0 5 0 5',
            autoFitErrors:false,//自动调整错误提示时候的宽度
            labelSeparator:' : ',
            labelWidth:80,
            width:550,
            labelAlign:'right',
            xtype:'textfield',
            allowBlank:false
        },
        items:[{
            xtype:'hiddenfield',
            name:'id'
        },{
            fieldLabel:'标题',
            name:'sqlTitle',
            id:'sqlTitle',
            maxLength:128,
            value:userPreTitle
        }/*,{
            xtype:'radiogroup',
            fieldLabel:'适用范围',
            columns:3,
            items:items
        }*/,{
            xtype:'textarea',
            name:'sqlContent',
            id:'sqlContent',
            fieldLabel:'SQL',
            height:270,
            value:sqlText
        }]
    });
    var saveUrl =  ((option == 'edit') ? rootUrl+'/dataManage/updateUserSql' : rootUrl+'/dataManage/saveUserSqlHandle');
    var optionText = ((option == 'edit') ? "修改" : "添加");
    if(editRecord) {
        form.loadRecord(editRecord);
        form.getForm().findField('sqlTitle').setValue(Ext.util.Format.htmlDecode(editRecord.get('sqlTitle')));
        form.getForm().findField('sqlContent').setValue(editSql['sqlContent']);
    }
    var win = new IDB.Window({
        height:420,width:600,title:optionText + '我的SQL',items:[form],
        buttons:[{
            text:optionText,handler:function() {
                if(form.isValid()) {
                    var values = form.getValues();
                    values.dbName = nowDBName;
                    //对使用范围就做当前数据库的默认为3
                     values.scopeApplication=3;
                    values.databaseId=dataBase_id;
                    values.datatableName=objectName;
                    win.getEl().mask('正在保存SQL....');
                    ajax({
                        url:saveUrl,
                        onlyUrl:true,
                        params:values,
                        success:function(resp) {
                            win.getEl().unmask();
                            var json = jsonDecode(resp.responseText);
                            if(json.success) {
                                Ext.Msg.alert('提示' , 'SQL保存成功！');
                                if(fn) {
                                    fn.call(this);
                                }
                                win.close();
                            }else {
                                Ext.Msg.alert('错误提示' , json.root);
                            }
                        },
                        failure:function(resp) {
                            win.getEl().unmask();
                        }
                    });
                }
            }
        },{
            text:'关闭',handler:function() {
                userPreTitle = Ext.getCmp('sqlTitle').getValue() || userPreTitle;
                win.close();
            }
        }]
    });
    Ext.getCmp('sqlTitle').focus(false , 100);
};
var addSQLValueForSelection = function(addSql,execute) {
    addSql = Ext.String.trim(addSql);
    if(addSql.charAt(addSql.length - 1) != ';') {
        addSql += ';';
    }
    var sqlArea = Ext.getCmp('tx_sql');
    var oldValue = sqlArea.getValue();
    var beforeLines = sqlArea.editor.lineCount();
    sqlArea.setValue(oldValue + "\n" + addSql + "\n");
    var endLines = sqlArea.editor.lineCount();
    var lastLength = sqlArea.editor.getLine(endLines - 1).length;
    focusInput();
    sqlArea.editor.setSelection({line:beforeLines,ch:0} , {line:(endLines - 1),ch:lastLength});
    if(execute) {
        executeSQL();
    }
};
/************user sql end******************/
var nowMsgContent = '';
var addMsgPanelContent = function(content) {
    if(!nowMsgContent) {
        nowMsgContent = content;
    }else {
        nowMsgContent += "\n\n\n\n" + content;
    }
    var dom = Ext.getCmp('execute_msg_area').el.dom;
    dom.innerHTML = '<pre>' + nowMsgContent + '</pre>';
    dom.scrollTop = dom.scrollHeight;
};
var clearMsgPanelContent = function() {
    nowMsgContent = '';
    var dom = Ext.getCmp('execute_msg_area').el.dom;
    dom.innerHTML = '';
};
var clearTabPanelResult = function() {
    var items = resultTabPanel.items;
    if(items.length > 1) {
        for(var i = items.length - 1 ; i > 0 ; i--) {
            resultTabPanel.remove(i,true);
        }
    }
};

//执行
var executeSQL = function() {
    var sqlText = Ext.String.trim(getSql());
    if (sqlText == "") {
        Ext.MessageBox.alert('提示', '请输入要执行的SQL！');
        return;
    }
    g_result_index = 0;
    resultWarning = false;
    isCancel = false;
    clearTabPanelResult();
    clearMsgPanelContent();
    Ext.getBody().mask('正在拆分SQL语句...');
    ajax({
        url:getRoot() + '/websql/splitSQL',
        params:{"sqlText":sqlText},
        success:function(resp) {
        	Ext.getBody().unmask();
            var json = jsonDecode(resp.responseText);
            if(json.success) {
                var data = json.root;
                var sqlArray  = data.sqlList;
                var timeDelay = data.timeDelay;
                addMsgPanelContent('\n\n【拆分SQL完成】：将执行SQL语句数量：（' + sqlArray.length + "条），拆分SQL耗时：（" + timeDelay + "ms.）");
                executeSQLDoing(sqlArray , 0);
            }else {
                Ext.Msg.alert('提示' , json.root);
            }
        },
        failure:function(resp) {
            Ext.getBody().unmask();
            Ext.Msg.alert('提示' , resp.responseText);
        }
    });
};
var trySetTabPanelToResult = function() {
    var items = resultTabPanel.items;
    if(items.length > 1) {
        resultTabPanel.setActiveTab(1);
    }
};
var resultWarning = false;
function showResult(sql , result) {
    var resultType = result['resultType'];//定义了结果类型，暂时不清楚 有几种类型
    if(resultType == 'tooManyResult' || result['displayColumns'].length < 1) {
        resultWarning = true;
    }else{
    	showResultSet(result , sql , resultType);//展示结果集
    }
}
function isNewRecord(grid, record) {
	var newRecords = grid.store.getNewRecords();
	return (newRecords && newRecords.indexOf(record) != -1);
}
function rendererResultValue(value, meta, record, rowIndex, colIndex, store, view, result_index) {
	var columnName = 'COLUMN_' + colIndex;
    var grid = Ext.getCmp('result_' + result_index);
    var metaData = grid.metadata[colIndex - 1];
    var v_primaryKeys = grid.editTablePrimaryKeys;
    var metaDataType = metaData['dataType'];

    if (!isNull(value) && (record.raw.hasOwnProperty(columnName) || record.data[columnName] !== '')) {
        if(v_primaryKeys && v_primaryKeys.length > 0 && metaDataType.indexOf('BLOB') != -1 && !isNewRecord(grid, record)) {
            return value + "<br/><a href='javascript:row_fun.downloadBlob("+ result_index + "," + colIndex  +")'>下载</a>" +
                " <a href='javascript:row_fun.uploadBlob("+ result_index + "," + colIndex + ")'>上传</a>";
        }
        return encodeValue(value, meta, record);
    } else {
        if(v_primaryKeys && v_primaryKeys.length > 0 && metaDataType.indexOf('BLOB') != -1 && !isNewRecord(grid, record)) {
            return '<i style=\"color:#E5E5E5;\">null</i>' + "<br/>" +
                " <a href='javascript:row_fun.uploadBlob("+ result_index + "," + colIndex + ")'>上传</a>";
        }
        // NULL值背景显示白灰色
        return '<i style=\"color:#E5E5E5;\">null</i>';
    }
}
var row_fun = {
	checkPrimaryKeys: function(gridResult, optionName) {
		var v_primaryKeys = gridResult.editTablePrimaryKeys;
		if (v_primaryKeys.length > 0) {
			return true;
		}
		Ext.Msg.alert('提示', '表没有主键，无法执行操作：【' + optionName + '】。');
		return false;
	},
	getRowValue: function(gridResult, key, row) {
		var realColumnName = grid_fun.findGridColumnNameByDBColumnName(gridResult, key);
		var modified = row.modified;
		return modified[realColumnName] || row.get(realColumnName);
	},
	downloadBlob: function(result_index, colIndex) {
		var gridResult = Ext.getCmp('result_' + result_index);	    
		var v_primaryKeys = gridResult.editTablePrimaryKeys;
        var metaData = gridResult.metadata[colIndex - 1];
        var metaDataColumnName = metaData['realName'];
        var selectedRows = gridResult.getSelectionModel().getSelection();
        if(selectedRows && selectedRows.length > 0 && row_fun.checkPrimaryKeys(gridResult, '下载BLOB')) {
            var v_primaryKeyValues = [] , selectedRow = selectedRows[0];
            Ext.each(v_primaryKeys , function(key) {
                v_primaryKeyValues.push(row_fun.getRowValue(gridResult, key , selectedRows[0]));
            });
            Ext.getBody().mask('正在进行后台导出中，请等待....');
            ajax({
                url:'/data/queryTable/exportBlob.do',
                timeout:(15 * 60 * 1000),
                params:{
                    dbName:metaData.dbName ,
                    tableName:metaData.tableName ,
                    columnName:metaDataColumnName ,
                    primaryKeys:v_primaryKeys,
                    primaryKeyValues:v_primaryKeyValues
                },
                success:function(resp) {
                    Ext.getBody().unmask();
                    var json = jsonDecode(resp.responseText);
                    if(json.success) {
                        downLoadFileByURL(json.root);
                    }else {
                        Ext.Msg.alert('提示' , json.root);
                    }
                },
                failure:function() {
                    Ext.getBody().unmask();
                }
            });
        }
	},
	uploadBlob:function(result_index, colIndex) {
		var gridResult = Ext.getCmp('result_' + result_index);
        var metaData = gridResult.metadata[colIndex - 1];
        var metaDataColumnName = metaData['realName'];
        var selectedRows = gridResult.getSelectionModel().getSelection();
        if(selectedRows && selectedRows.length > 0 && row_fun.checkPrimaryKeys(gridResult, '上传BLOB')) {
            var items = [
                {
                    xtype:'filefield',
                    name:'file',
                    fieldLabel:'附件',
                    blankText:'附件不能为空',
                    buttonText:'选择文件'
                },
                {name:'dbName',hidden:true,value:metaData.dbName},
                {name:'tableName',hidden:true,value:metaData.tableName},
                {name:'columnName',hidden:true,value:metaDataColumnName}
            ];
            var v_primaryKeys = gridResult.editTablePrimaryKeys;
            Ext.each(v_primaryKeys , function(key) {
                items.push(
                    {name:'primaryKeys',hidden:true,value:key},
                    {name:'primaryKeyValues',hidden:true,value:row_fun.getRowValue(gridResult, key ,selectedRows[0])}
                );
            });

            var form = new IDB.FormPanel({
                defaults:{width:540,margin: '5 2 2 0',columnWidth:1},
                fileUpload:true,
                layout:'column',
                items:items
            });
            var win = new IDB.Window({
                width:520 , height:115 , title:'文件上传',
                items:[form],
                buttons:[
                    {
                        text:'上传',handler:function() {
                        if(form.isValid()) {
                            form.getForm().submit({
                                waitMsg: '正在导入数据，上传时间取决于文件大小及网速，请耐心等待....',
                                timeout:10 * 60 * 1000,
                                url:'/data/sqlWindow/importBlob.do?token=' + getUserToken(),
                                success:function(fp,o) {
                                    var json = o.result;
                                    if(json.success) {
                                        selectedRows[0].set(grid_fun.findGridColumnNameByDBColumnName(gridResult, metaDataColumnName) , '[BLOB]');
                                        win.close();
                                    }else if(json.root) {
                                        Ext.Msg.alert('服务器端错误', json.root);
                                    }else if(json.indexOf("Request Entity Too Large") != -1) {
                                        Ext.Msg.alert('提示' , '上传的数据太大，请检查你所上传的数据是否已经超过8M的限制。');
                                    }
                                },
                                failure:function(fp,o) {
                                    try {
                                        if(o.result.root) {
                                            Ext.Msg.alert('错误提示' , o.result.root);
                                        }else if(String(o.result).indexOf("Request Entity Too Large") != -1) {
                                            Ext.Msg.alert('提示' , '上传的数据太大，请检查你所上传的数据是否已经超过8M的限制。');
                                        }
                                    }catch(e) {
                                        Ext.Msg.alert('未知错误' , jsonToString(o.result))
                                    }
                                }
                            });
                        }
                    }
                    },{
                        text:'取消',handler:function() {win.close()}
                    }
                ]
            })
        }
    }
}
var grid_fun = {
	findGridColumnNameByDBColumnName: function(gridResult, dbColumnName) {
		var find = false, findColumnName = null;
		Ext.each(gridResult.metadata, function(meta) {
			if (!find && meta['realName'] == dbColumnName) {
				findColumnName = meta['name'];
				find = true;
			}
		});
		return findColumnName;
	}
};
function rendererRowResultValue(value, meta, record, rowIndex, colIndex) {
    if (!isNull(value)) {
        return encodeValue(value, meta, record);
    } else {
        // NULL值背景显示白灰色
        return '<i style=\"color:#E5E5E5;\">null</i>';
    }
}

var executeSQLDoing = function(sqlArray , index) {
    if(index >= sqlArray.length) {
        addMsgPanelContent("");
        if(!resultWarning) {
            trySetTabPanelToResult();
        }
        return;
    }
    var sql = sqlArray[index];
    cancelWindow.items.get(0).setText("正在执行：<br/><br/>" + sql.htmlEncode(), false);
    cancelWindow.show();
    var realSQL = Ext.util.Format.htmlDecode(sql);
    var paramsValue;
    if(isLocal=='isLocal'){
    	paramsValue={dbName:nowDBName,"dataId":dataBase_id,"baseType":base_type,"dataSourceId":dataSource_id,"dataSource":data_source,"sql":realSQL,isLocal:isLocal}
    }else{
    	paramsValue={dbName:nowDBName,"dataId":dataBase_id,"baseType":base_type,"dataSourceId":dataSource_id,"dataSource":data_source,"sql":realSQL}
    }
    ajax({
        timeout:3600000 * 24,
        url:getRoot() + '/websql/executeSQL',
        params:paramsValue,
        success:function(resp) {
        	var json = jsonDecode(resp.responseText);
            var panelMsg;
            if(json.success) {
                panelMsg = json.root['msg'];
                showResult(sql ,json.root);
                addMsgPanelContent("【执行SQL：(" + (index + 1) + ")】\n\n<span style='font-size: 12px;font-weight: bold;'>" + sql.htmlEncode() + "</span>\n\n" + panelMsg);
                cancelWindow.hide();
                
                if(!isCancel) {
                	executeSQLDoing(sqlArray , index + 1);
                }
            }else {
            	if(isLocal=='isLocal'){
            		var msg = "SQL语句执行失败：<br/>" + sql.htmlEncode() + "<br/><br/>失败原因：" + json.root;
                    panelMsg = "执行失败，失败原因：" + json.root;
                    addMsgPanelContent("【执行SQL：(" + (index + 1) + ")】\n\n<span style='font-size: 12px;font-weight: bold;'>" + sql.htmlEncode() + "</span>\n\n" + panelMsg);
                    cancelWindow.hide();
                    
                    if(index < sqlArray.length - 1) {
                         msg += "<br/><br/>后续还有部分SQL尚未执行，请选择是否继续执行。";
                         Ext.Msg.confirm('错误提示' , msg , function(v) {
                             if(v == 'yes') {
                            	 isCancel = false;
                            	 executeSQLDoing(sqlArray , index + 1);
                             }
                         });
                    }else {
                        Ext.Msg.alert('错误提示' , msg);
                    }
            	}else{
            		cancelWindow.hide();
            		if(json.failure){
            			$.feedbackMessage({
                            type: 'success',
                            message: json.root,
                            showTime:6000
                        });
            		}
            		if(!json.failure){
            			$.feedbackMessage({
                            type: 'danger',
                            message: json.root,
                            showTime:8000
                        });
            		}
            	}
                
            }

        },
        failure:function(resp) {
        	 cancelWindow.hide();
            Ext.Msg.alert(resp.responseText);
        }
    });
};
function getResultStatusBar(resultType,result,initConfig) {
    var barConfig = [{
        text:'单行详情',handler:function() {
            showRowContent(initConfig.result_index);
        }
    }];
    var _result_index = initConfig.result_index;
    var cellEditor = initConfig.cellEditor;
    if(result['canEdit']) {
        barConfig.push({
            text:'新增',iconCls:'add',id:'add_icon_' + _result_index,handler:function() {
                cellEditor.completeEdit();
                addRecord(_result_index);
            }
        },{
            text:'删除',iconCls:'delete',id:'del_icon_' + _result_index,handler:function() {
                cellEditor.completeEdit();
                deleteRecord(_result_index);
            }
        },{
            text:'提交修改',iconCls:'accept',id:'accept_icon_' + _result_index,handler:function() {
                cellEditor.completeEdit();
                showEditDataSql(_result_index);
            }
        });
    }

    //查询
//    if(isQuery(result['sqlType'])) {
//        barConfig.push( {
//                text:'导出数据',
//                id:'bn_export_' + _result_index,
//                iconCls:'export',
//                hidden:isLimitAllExport,
//                disabled:isQuery(result['sqlType']) ? false : true,
//                menu:[
//                    {
//                        text:'导出更多数据',hidden:isLimitExport,handler:function() {
//                        exportMoreData(_result_index);
//                    }
//                    },{
//                        text:'导出CSV（最多' + EXPORT_MAX_ROWS_NAME + '）',
//                        handler:function () {
//                            exportResult('csv',_result_index);
//                        }
//                    },
//                    {
//                        text:'导出Insert SQL（最多' + EXPORT_MAX_ROWS_NAME +  '）',
//                        handler:function () {
//                            exportResult('sql',_result_index);
//                        }
//                    }
//                ]
//            },
//            {
//                text:'导出数据',hidden:!isLimitExportUrl,
//                menu:[{
//                    text:'导出数据被屏蔽 点击查看详情',handler:function() {
//                        window.parent.onbeforeunload = null;
//                        window.parent.location = limitExportUrl;
//                    }
//                }]
//            });
//    }
    if(resultType != 'metadata') {
        if(result['canEdit']) {
            barConfig.push({
                xtype:'label',
                text:'【表格数据可以编辑】'
            });
        }else {
        	if(result['canNotEditReason'] != null){
        		barConfig.push({
                    xtype:'label',
                    text:'【表格数据不能编辑】：' + result['canNotEditReason']
                });
        	}
        }
    }
    return barConfig;
}
function getResultTBar(resultType,result,initConfig) {
	var _result_index = initConfig.result_index;
    var barConfig = [];
    if(resultType == 'metadata') {
        barConfig.push('【消息】：输出元数据信息，不能编辑或翻页。');
    }else {
        var cellEditor = initConfig.cellEditor;
        var pageSizeStore = new Ext.data.Store({
            fields:['data'],
            data:pageSizeArray,
            proxy: {
                type: 'memory'
            }
        });
        barConfig.push({
            iconCls:'page_first',toolTip:'第一页',handler:function() {
                if(setFirstPage(initConfig.result_index)) {
                    getPageResult(initConfig.result_index);
                }
            }
        },{
            iconCls:'page_prev',toolTip:'前一页',handler:function() {
                if(nextPage(-1 , initConfig.result_index)) {
                    getPageResult(initConfig.result_index);
                }
            }
        },'当前页：',{
            xtype:'numberfield',
            allowDecimals:false,
            id:'page_num_' + initConfig.result_index,
            width:50,
            minValue:1,
            value:1,
            negativeText:'不允许输入负数',
            nanText:'无效数字字符'
        },{
            text:'GO',handler:function() {
                var grid = Ext.getCmp('result_' + initConfig.result_index);
                var pageNum = Ext.getCmp('page_num_' + initConfig.result_index);
                if(!pageNum.isValid()) {
                    pageNum.setValue(grid.now_page_index);
                }
                getPageResult(initConfig.result_index);
            }
        },{
            iconCls:'page_next',toolTip:'下一页',handler:function() {
                if(nextPage(1 , initConfig.result_index)) {
                    getPageResult(initConfig.result_index);
                }
            }
        },'每页：',
            {
                xtype:'combo',
                id:'page_size_' + initConfig.result_index,
                triggerAction:'all',
                displayField:'data',
                valueField:'data',
                queryMode:'local',
                forceSelection:false,
                editable:false,
                width:65,
                typeAhead:true,
                value:10,
                store:pageSizeStore,
                allowBlank:false,
                listeners:{
                    select:function() {
                        getPageResult(initConfig.result_index);
                    }
                }
            },'-');

        //能否编辑时，消息显示的是不一样的
        barConfig.push({
            xtype:'label',
            text:"【消息】：" + result['msg']
        });
    }
    return barConfig;
}
function moveRowResult(option,grid) {
    var selectionModel = grid.getSelectionModel();
    if (option == 'first') {
        selectionModel.select(0);
    } else if (option == 'last') {
        selectionModel.select(grid.store.getCount() - 1);
    } else if (option == 'previous') {
        selectionModel.select(grid.store.indexOf(selectionModel.lastSelected) - 1);
    } else if (option == 'next') {
        selectionModel.select(grid.store.indexOf(selectionModel.lastSelected) + 1);
    }
}
function getPageResult(result_index) {
    var grid = Ext.getCmp('result_' + result_index);
    var pageNum = Ext.getCmp('page_num_' + result_index);
    var pageSize = Ext.getCmp("page_size_" + result_index);
    var page_num = pageNum.getValue();
    var page_size = pageSize.getValue();
    Ext.getBody().mask('正在获取以下SQL的第（' + page_num + "）分页数据。<br/><br/>" + grid.sql.htmlEncode());
    var paramsValue;
    if(isLocal=='isLocal'){
    	paramsValue={dbName:grid.editDbName,"dataId":dataBase_id,"baseType":base_type,"dataSourceId":dataSource_id,"dataSource":data_source,"sql":grid.sql, pageNum:page_num , pageSize:page_size,isLocal:isLocal}
    }else{
    	paramsValue={dbName:grid.editDbName,"dataId":dataBase_id,"baseType":base_type,"dataSourceId":dataSource_id,"dataSource":data_source,"sql":grid.sql, pageNum:page_num , pageSize:page_size}
    } 
    ajax({
    	url:getRoot() + '/websql/executeSQL',
        params:paramsValue,
        success:function(resp) {
            Ext.getBody().unmask();
            var json = jsonDecode(resp.responseText);
            var panelMsg;
            if(json.success) {
                grid.now_page_index = page_num;
                grid.now_page_size = page_size;
                panelMsg = json.root['msg'];
                showPageResult(json.root , grid , page_num , page_size);
            }else {
                pageNum.setValue(grid.now_page_index);
                pageSize.setValue(grid.now_page_size);
                panelMsg = "执行失败，失败原因：" + json.root;
                Ext.Msg.alert('错误提示' , json.root);
            }
            addMsgPanelContent("【提取SQL的第（" + grid.now_page_index +"）页数据】\n\n<span style='font-size: 12px;font-weight: bold;'>" + grid.sql + "</span>\n\n" + panelMsg);
        },
        failure:function(resp) {
            Ext.getBody().unmask();
            Ext.Msg.alert('提示' , resp.responseText);
        }
    });

}

function showPageResult(result , grid , page_num , page_size) {
    var startIndex = (page_num - 1) * page_size;
    result.displayColumns[0].renderer = function (value, metadata, record, rowIndex) {
        return rowIndex + 1 + startIndex;
    };
    for (var i = 1; i < result.displayColumns.length; i ++) {
    	result.displayColumns[i].renderer = function(value, meta, record, rowIndex, colIndex, store, view) {
    		return rendererResultValue(value, meta, record, rowIndex, colIndex, store, view, g_result_index);
    	}
    }
    var store = Ext.create('Ext.data.Store', {
        fields:grid.metadata
    });
    grid.reconfigure(store , result.displayColumns);
    store.loadRawData(result.data, true);
    var length = String(startIndex + 100).length;
    grid.getView().getHeaderCt(1).getHeaderAtIndex(0).setWidth(length * 10 + 8);
    moveRowResult("first" , grid);
    if(grid.editTableName) {
        setColumnEditor(grid);
        edit_option_fun.enableEditIcons(grid.result_index);
    }
}

/**
 * 分页展示数据结果
 * */
function showResultSet(result , sql , resultType) {
    var res_index = ++g_result_index;
    for (var i = 1; i < result.displayColumns.length; i++) {
        result.displayColumns[i].renderer = function(value, meta, record, rowIndex, colIndex,store,view) {
            return rendererResultValue(value, meta, record, rowIndex, colIndex,store,view , res_index);
        };
    }
    var store = Ext.create('Ext.data.Store', {
        fields:result.metadata
    });
    var cellEditor = Ext.create('Ext.grid.plugin.CellEditing', {
        clicksToEdit:1
    });
    var grid = Ext.create('Ext.grid.Panel' , {
        title:'结果集' + res_index,
        id:'result_' + res_index,
        itemId:'result_' + res_index,
        sortableColumns:false,
        multiSelect:true,
        tabConfig:{
            tooltip:"SQL:" + sql.htmlEncode()
        },
        store:store,
        viewConfig:{ stripeRows:true, enableTextSelection:true},
        columns:result.displayColumns,
        plugins:[
            cellEditor
        ],
        tbar:getResultStatusBar(resultType , result , {result_index:res_index , cellEditor:cellEditor}),
        bbar:getResultTBar(resultType , result , {result_index:res_index , cellEditor:cellEditor}),
        listeners:{
            afterrender:function() {
                moveRowResult("first" , grid);
                if(result['canEdit'] && !grid.columnEditor) {
                    setColumnEditor(grid);
                    grid.columnEditor = true;
                }
            }
        },
        displayEdit:function() {

        }
    });
    grid.result_index = res_index;
    grid.now_page_index = 1;
    grid.now_page_size = 10;
    grid.sql = sql;
    grid.dbName = nowDBName;
    grid.metadata = result.metadata;
    if(result['canEdit']) {
        grid.editTablePrimaryKeys = result.editTablePrimaryKeys;
        grid.editTableName = result.editTableName;
        grid.editDbName = result.editDbName;
    }
    grid.columnEditor = false;
    store.loadRawData(result.data, true);
    resultTabPanel.add(grid);
}

//消息 tab输出框
var createResultMessagePanel = function() {
    return new Ext.tab.Panel({
        region:'center',
        tabPosition:'top',
        activeTab:0,
        items:[
            {
                title:'消息',
                xtype:'container',
                border:false,
                autoScroll:true,
                baseCls:'execute_msg_content',
                id:'execute_msg_area'
            }
        ]
    });
};

Ext.onReady(function () {
    init();
});
if(window.parent) {
    parentPanelKey = window.parent.getPaneKey();
}
//初始化DB列表
var initDBList = function() {
    dbList = new IDB.CommonBox({
        width:165,
        loadSelectFirst:true,
        url:getRoot() + '/websql/getDataBase?dataId='+dataBase_id+'&baseType='+base_type+'&dataSourceId='+dataSource_id+'&dataSource='+data_source+'&isLocal='+isLocal,
        loadCallBack:function (combo) {
            if (nowDBName) {
                if(dbList.store.find('data' , nowDBName) != -1) {
                    dbList.setValue(nowDBName);
                }else {
                    dbList.selectFirst();
                    nowDBName = combo.getValue();
                }
            } else {
                nowDBName = combo.getValue();
            }
        },
        selectCallBack:function (combo) {
            nowDBName = combo.getValue();
            updateTableOptionsObject(nowDBName);
        },
        listConfig:{
            getInnerTpl:function () {
                return '<div title="{data}">{data}</div>';
            }
        }
    });
};

function setTableOptionsObject(comboValue) {
	var tmpNowDBName = comboValue ? comboValue : nowDBName;
	ajax({//发送同步请求
		async:false,
		url:getTableColumnUrl(),
        params:{dbName:tmpNowDBName},
        success:function(resp) {
        	var json = jsonDecode(resp.responseText);
        	if (json.success) {
        		var jsonData = json.tables;
        		var databaseData = json.databases;
        		CM_NOW_DATABASE = tmpNowDBName;
        		var tableData = jsonData;
        		var databaseResObj = {};
        		var tableResObj = {};
        		for (var i = 0; i < databaseData.length; i ++) {
        			databaseResObj[databaseData[i]] = null;
        		}
        		for (var i = 0; i < tableData.length; i ++) {
        			var tmpName = tableData[i];
        			var tmpComment = null;
        			tableResObj[tmpName] = {"__cm__comment":tmpComment};
        		}
        		CM_TABLES = tableResObj;
        		databaseResObj[CM_NOW_DATABASE] = CM_TABLES;
        		CM_DATABASES = databaseResObj;
        		Ext.getCmp('tx_sql').editor.setOption('hintOptions', {databases:databaseResObj, tables:tableResObj});
        	}
        }
    });
};

function updateTableOptionsObject(comboValue) {
	var tmpNowDBName = comboValue ? comboValue : nowDBName;
	if (tmpNowDBName && CM_DATABASES.hasOwnProperty(tmpNowDBName)) {
		CM_NOW_DATABASE = tmpNowDBName;
		if (CM_DATABASES[CM_NOW_DATABASE]) {
			CM_TABLES = CM_DATABASES[CM_NOW_DATABASE];
		} else {
			ajax({
				async:false,
				url:getTableColumnUrl(),
				params:{type:"table_group", dbName:tmpNowDBName},
				success:function(resp) {
					var json = jsonDecode(resp.responseText);
					if (json.success) {
						var tableData = json.root;
						var tableResObj = {};
						for (var i = 0; i < tableData.length; i ++) {
							var tmpName = tableData[i].realText;
							var tmpComment = k;
							tableResObj[tmpName] = {"__cm__comment":tmpComment};
						}
						CM_TABLES = tableResObj;
						CM_DATABASES[CM_NOW_DATABASE] = CM_TABLES;
					}
				}
			});
		}
	}
}

function setUserPromptPrefer(newValue) {
	ajax({
		async:true,
		url:"/userConfig/saveUserPreferConfig.do?onlyUrl=true",
		params:{"inputSqlAutoComplete":newValue},
		success:function(resp) {
		}
	});
	
}

var tunningSQLItem;
var tunningTabPanel;

function init() {
    Ext.QuickTips.init();
    initDBList();
    
    /**
     * Config support SQLTunning
     * 1.Tunning SQLButton
     * 2.Tunning SQL List
     */
    tunningSQLItem = isSupportTunningSQL == 'on' ? {text:'优化', xtype:'button',tooltip:'该功能可以为您的慢SQL提供索引建议、检测隐式转换。', iconCls:'tunning', handler:function() {tunningSQL("sqlwindow") }} : null;
    tunningTabPanel = isSupportTunningSQL == 'on' ? {title:'优化列表', itemId:'tunningTabPanel', layout:'fit', items :[tunningPanel]} : null;
    
    resultTabPanel = createResultMessagePanel()
    
    
    var containsTab = false;
    if(nowTableName) {
        initSQL = "select * from `" + nowTableName.replaceAll("`" , "``") + "` limit 0,50";
        containsTab = true;
    }
        
    Ext.create('Ext.Viewport', {
        layout:{
            type:'border',
            padding:0
        },
        defaults:{
            split:true
        },
        items:[tabPanelTpl, {region:'center', layout:'border',
            items:[
                {
                    id:'pnl_top',
                    region:'north',
                    border:0,
                    layout:'fit',
                    split:true,
                    height:100,
                    minHeight:60,
                    tbar:[
                        {
                            text:'执行(F8)',
                            id:'bn_Execute',
                            xtype:'button',
                            iconCls:'execute',
                            handler:function () {
                               executeSQL();
                            }
                        },
                        tunningSQLItem
                        ,
                        {
                            text:'格式化',
                            xtype:'button',
                            iconCls:'format',
                            handler:function () {
                                formatSql();
                            }
                        }
                        ,
                        {
                            text:'执行计划',
                            xtype:'button',
                            iconCls:'format',
                            handler:function () {
                            	showSqlPlan();
                            }
                        }
                        ,
                        {xtype:'label', text:'数据库：'},
                        dbList,
                        {
                            iconCls:'fa fa-refresh',
                            handler:function () {
                                var selectValue = dbList.getValue();
                                dbList.store.load({callback:function (records, operation, success) {
                                    if (success) {
                                        dbList.setValue(selectValue);
                                    }
                                }});
                            }
                        },
                        {
                            text:'我的SQL',
                            menu:new Ext.menu.Menu({
                                listeners:{
                                    beforeshow:function() {
                                        setChildMenu();
                                    }
                                },
                                items:[{
                                    text:'添加我的SQL',handler:function() {saveUserSQL('add' , '')}
                                },{
                                    text:'选择我的SQL',id:'checkUserSQL',hidden:true
                                },{
                                    text:'管理我的SQL',handler:manageUserSQL
                                }]
                            })
                        },
                        {
                        	xtype:'checkboxfield',
                            id:'sqlPrompt',
                            boxLabel:'仅输入时提示SQL',
                            checked: onlyInputPrompt,
                            listeners:{
                                change:function(thiz,newValue,oldValue) {
                                	onlyInputPrompt = newValue;
                                	setUserPromptPrefer(newValue);
                                }
                            }
                        }
                        
                    ],
                    items:[
                        {
                            xtype:'codemirror',
                            id:'tx_sql',
                            name:'test',
                            border:0,
                            value:'SELECT * FROM ',
                            listeners:{
                                keyevent:function (o, event) {
                                    if (event.keyCode == 119 && event.type == 'keyup') {// F8
                                        executeSQL();
                                    } else if (event.keyCode == 120 && event.type == 'keyup') {// F9
                                        formatSql();
                                    }
                                },
                                resize:function (o, width, height, oldWidth, oldHeight, eOpts) {
                                }
                            }
                        }
                    ]
                },
                resultTabPanel
            ]
        }
        ]
    });
    if (useAutoCompletion) {//AutoComplete开关
    	setTableOptionsObject();//初始化表(AutoComplete)
    }
    initQuery();
    focusInput();
    var sqlTextTarget = new Ext.dd.DropTarget(Ext.getCmp('tx_sql').getEl(), {group:'sqlText'});
   
    
    if(containsTab) {
        executeSQL();
    }
    if (document.body.clientHeight > 600) {
        Ext.getCmp('pnl_top').setHeight(200);
    } else if (document.body.clientHeight > 500) {
        Ext.getCmp('pnl_top').setHeight(150);
    }
    var setSQLById = function(id) {
        Ext.getBody().mask('正在加载SQL...');
        ajax({
            url:'/userConfig/getUserSQLContentById.do',
            onlyUrl:true,
            params:{id:id},
            success:function(resp) {
                Ext.getBody().unmask();
                var json = jsonDecode(resp.responseText);
                if(json.success) {
                    addSQLValueForSelection(json.root);
                    // sqlArea.editor.replaceSelection("select 1");
                }else {
                    Ext.Msg.alert('错误提示' , json.root);
                }
            },
            failure:function() {Ext.getBody().unmask();Ext.Msg.alert('提示' , 'SQL加载失败..');}
        })
    };
    var setChildMenu = function() {
        ajax({
            url:rootUrl+'/dataManage/showUserSql',
            onlyUrl:true,
            params:{databaseId:dataBase_id,datatableName:objectName},
            success:function(response) {
            	var json = jsonDecode(response.responseText);
                if(json.success) {
                	console.log(json);
                    var items = [];
                    Ext.each(json.list , function(row) {
                        items.push({
                            text:row['sqlTitle'],handler:function() {
                            	addSQLValueForSelection(row['sqlContent']);
                                //setSQLById(row.id);
                            }
                        }) ;
                    });
                    if(items.length > 0) {
                        Ext.getCmp('checkUserSQL').show();
                        Ext.getCmp('checkUserSQL').setMenu(new Ext.menu.Menu({
                            items:items
                        }));
                    }else {
                        Ext.getCmp('checkUserSQL').hide();
                        Ext.getCmp('checkUserSQL').setMenu(new Ext.menu.Menu({
                            items:[]
                        }));
                    }
                }
            }
        });
    };
}

function setColumnEditor(grid) {
    var dbName = grid.editDbName;
    var tableName = grid.editTableName;
    var fields = grid.store.model.getFields();
    var columns = grid.columnManager.getColumns();
    for (var i = 0; i < columns.length; i ++) {
        var column = columns[i];
        if (i > 0) {
            for (var j = 0; j < fields.length; j ++) {
                var field = fields[j];
                if (field.name == column.dataIndex) {
                    if (!field.readOnly && field.tableName == tableName && field.dbName == dbName) {
                    	if (isNumberDataType(field.dataType) && !Ext.isIE) {
							column.setEditor({
								xtype: "numberfield",
								decimalPrecision: 20
							})
						} else {
							if (field.dataType == "DATE") {
								column.setEditor("idbdatefield")
							} else {
								if (field.dataType == "DATETIME" || field.dataType == "TIMESTAMP") {
									column.setEditor("datetimefield")
								} else {
									if (field.dataType.indexOf("BLOB") >= 0) {
										column.setEditor(null)
									} else {
										if (field.size >= 10000) {
											column.setEditor("idbtextarea")
										} else {
											column.setEditor("mixEditor")
										}
									}
								}
							}
						}
                    }
                }
            }
        }
    }
}

var nextPage = function(num , result_index) {
    var grid = Ext.getCmp('result_' + result_index);
    var pageNum = Ext.getCmp('page_num_' + result_index);
    var nowNum = 0;
    if(!pageNum.isValid()) {
        nowNum = grid.now_page_index + num;
    }else {
        nowNum = pageNum.getValue() + num;
    }
    if(nowNum > 0) {
        pageNum.setValue(nowNum);
        return true;
    }else {
        Ext.Msg.alert('提示' , '当前已经是第1页');
        return false;
    }
};
var setFirstPage = function(result_index) {
    var grid = Ext.getCmp('result_' + result_index);
    var pageNum = Ext.getCmp('page_num_' + result_index);
    if(pageNum.isValid() && pageNum.getValue() == 1) {
        Ext.Msg.alert('提示' , '当前已经是第1页');
        return false;
    }
    pageNum.setValue(1);
    return true;
};
var edit_option_fun = {
	    disableEditIcons:function(result_index) {
	        Ext.getCmp('add_icon_' + result_index).disable();
	        Ext.getCmp('del_icon_' + result_index).disable();
	        Ext.getCmp('accept_icon_' + result_index).disable();
	    },
	    enableEditIcons:function(result_index) {
	        Ext.getCmp('add_icon_' + result_index).enable();
	        Ext.getCmp('del_icon_' + result_index).enable();
	        Ext.getCmp('accept_icon_' + result_index).enable();
	    },
	    disableEditor:function(result_index) {
	        var grid = Ext.getCmp('result_' + result_index);
	        var columns = grid.columnManager.getColumns();
	        for (var i = 0; i < columns.length; i ++) {
	            var column = columns[i];
	            column.setEditor(null);
	        }
	    },
	    disableGridEdit:function(result_index) {
	        edit_option_fun.disableEditor(result_index);
	        edit_option_fun.disableEditIcons(result_index);
	    }
	};

var showRowContent = function(result_index) {
    var grid = Ext.getCmp('result_' + result_index);
    var dataStore = new Ext.data.Store({
        fields:["columnName", "columnValue", "dataType"]
    });
    var selectionRow = grid.getSelectionModel().getSelection()[0];
    if(!selectionRow) {
        return Ext.Msg.alert('提示' , '没有选择任何数据!');
    }
    var setStoreData = function() {
        selectionRow = grid.getSelectionModel().getSelection()[0];
        dataStore.removeAll();
        for (var i = 0; i < selectionRow.fields.items.length; i ++) {
            var field = selectionRow.fields.items[i];
            if (field.name.substr(0, 7) == "COLUMN_") {
                dataStore.add({
                    columnName:field.label,
                    columnValue:selectionRow.data[field.name],
                    dataType:getDataTypeStr(field.dataType, field.size)
                });
            }
        }
        updateRowResultStatus();
    };
    var contentGrid = new Ext.grid.Panel({
        store:dataStore,
        region:'center',
        sortableColumns:false,
        deferRowRender:false,
        viewConfig:{ stripeRows:true, enableTextSelection:true},
        columns:[
            Ext.create('Ext.grid.RowNumberer', {width:30}),
            {text:"字段名", dataIndex:"columnName", width:200},
            {text:"值", dataIndex:"columnValue", width:500, renderer:rendererRowResultValue},
            {text:"类型", dataIndex:"dataType", width:200}
        ]
    });
    var win = new IDB.Window({
        title:'单行详情',
        items:[contentGrid],
        width:964,
        height:420,
        maximizable:true,
        closable:true,
        buttons:[{
            text:'第一条',
            id:'bn_moveFirstRow',
            disabled:true,
            handler:function () {
                moveRowResult('first' , grid);
                setStoreData();
            }
        },{
            text:'上一条',id:'bn_movePreviousRow',handler:function() {
                moveRowResult('previous' , grid);
                setStoreData();
            }
        },{
            text:'下一条',id:'bn_moveNextRow',handler:function() {
                moveRowResult('next' , grid);
                setStoreData();
            }
        },{
            text:'最后一条',id:'bn_moveLastRow',handler:function() {
                moveRowResult('last' , grid);
                setStoreData();
            }
        }]
    });
    function updateRowResultStatus() {
        var selection = grid.getSelectionModel().getSelection()[0];
        if (selection) {
            var selectionId = grid.getStore().indexOf(selection);
            var isFirst = (selectionId <= 0);
            var isLast = (selectionId >= grid.store.getCount() - 1);
            if (isFirst) {
                Ext.getCmp('bn_moveFirstRow').disable();
                Ext.getCmp('bn_movePreviousRow').disable();
            } else {
                Ext.getCmp('bn_moveFirstRow').enable();
                Ext.getCmp('bn_movePreviousRow').enable();
            }
            if (isLast) {
                Ext.getCmp('bn_moveNextRow').disable();
                Ext.getCmp('bn_moveLastRow').disable();
            } else {
                Ext.getCmp('bn_moveNextRow').enable();
                Ext.getCmp('bn_moveLastRow').enable();
            }
        }
    }
    setStoreData();
};
function addRecord(result_index) {
    var grid = Ext.getCmp('result_' + result_index);
    var fields = grid.store.model.getFields();
    var newRecord = grid.store.add({'__new':1})[0];// 在最后一个位置插入
    grid.getView().scrollBy(0, 10000000);
    grid.getView().refresh();
    grid.getSelectionModel().select(grid.store.getCount() - 1);
    //设置默认值
    for (var i = 0; i < fields.length; i++) {
        if (grid.editTableName == fields[i].tableName && grid.editDbName == fields[i].dbName) {
            var columnName = fields[i].realName;
            var defaultValue = getColumnDefaultValue(columnName , grid);
            if (defaultValue != undefined) {
                newRecord.set(fields[i].name, defaultValue);
            }
        }
    }
}
function getDataTypeStr(dataType, size) {
    dataType = dataType + '(' + size + ')';
    return dataType.toLowerCase();
}
function getColumnDefaultValue(columnName,grid) {
	return "";
    
}
function deleteRecord(result_index) {
    var grid = Ext.getCmp('result_' + result_index);
    var selection = grid.getSelectionModel().getSelection();
    if (selection.length <= 0) {
        Ext.MessageBox.alert('提示', '请选择要删除的记录');
        return;
    }
    for (var i = 0; i < selection.length; i++) {
        grid.store.remove(selection[i]);
    }
}
var update_sql_fun = {
    deleteSQL:function(tableName , grid) {
        var allSql = new Array();
        var primaryKeys = grid.editTablePrimaryKeys;
        var records = grid.getStore().getRemovedRecords();
        Ext.each(records , function(record) {
            var whereStr = '';
            var oldValues = record.modified;
            var fields = record.fields;
            var rowIndex = grid.getStore().indexOf(records);
            Ext.each(fields.items , function(field) {
                var columnName = field.name;
                var realName = field.realName;
                if (realName && primaryKeys.length > 0 && primaryKeys.indexOf(realName) != -1) {
                    if (whereStr != '') {
                        whereStr = whereStr + ' and ';
                    }
                    var pkOldValue = oldValues[columnName];
                    if (pkOldValue == undefined) {
                        pkOldValue = record.data[columnName];
                    }
                    if (isNoZeroEmpty(pkOldValue)) {
                        Ext.Msg.alert('提示', '第' + (rowIndex + 1) + '行主键[' + field.realName + ']不能为空！');
                        return;
                    }
                    whereStr = whereStr + '`' + field.realName + "`=" + getFieldValueStr(pkOldValue, field.dataType);
                }
            });
            var sql = 'delete from ' + tableName + ' where ' + whereStr + ';';
            allSql.push({rowIndex:rowIndex, type:'D', sql:sql});
        });
        return allSql;
    },
    insertSQL:function(tableName , grid) {
        var allSql = new Array();
        var records = grid.getStore().getModifiedRecords();
        Ext.each(records , function(record) {
            var sql = '';
            var oldValues = record.modified;
            var newValues = record.getChanges();
            if (record.raw.__new == 1) {
                var insertColumnNames = '';
                var insertColumnValues = '';
                var rowIndex = grid.getStore().indexOf(record);
                Ext.each(record.fields.items , function(field) {
                    var columnName = field.name;
                    if (oldValues[columnName] !== undefined) {
                        if (insertColumnNames != '') {
                            insertColumnNames = insertColumnNames + ',';
                            insertColumnValues = insertColumnValues + ',';
                        }
                        insertColumnNames = insertColumnNames + '`' + field.realName.replaceAll("`" , "``") + '`';
                        insertColumnValues = insertColumnValues + getFieldValueStr(newValues[columnName], field.dataType);
                    }
                });
                if (insertColumnNames != '') {
                    sql = 'insert ' + tableName + '(' + insertColumnNames + ') values(' + insertColumnValues + ');';
                    allSql.push({rowIndex:rowIndex, type:'I', sql:sql});
                }
            }
        });
        return allSql;
    },
    updateSQL:function(tableName , grid) {
        var allSql = new Array();
        var records = grid.getStore().getModifiedRecords();
        var primaryKeys = grid.editTablePrimaryKeys;
        Ext.each(records , function(record) {
            var sql = '' , whereStr = '';
            var oldValues = record.modified;
            var newValues = record.getChanges();
            if (record.raw.__new != 1) {
                var rowIndex = grid.getStore().indexOf(record);
                Ext.each(record.fields.items , function(field) {
                    var columnName = field.name;
                    var realName = field.realName;
                    if (oldValues[columnName] !== undefined) {//set
                        if (sql != '') {
                            sql = sql + ',';
                        }
                        sql = sql + '`' + field.realName + "`=" + getFieldValueStr(newValues[columnName], field.dataType);
                    }

                    if (realName && primaryKeys.length > 0 && primaryKeys.indexOf(realName) != -1) {//where
                        if (whereStr != '') {
                            whereStr = whereStr + ' and ';
                        }
                        var pkOldValue = oldValues[columnName];
                        if (pkOldValue == undefined) {
                            pkOldValue = record.data[columnName];
                        }
                        if (isNoZeroEmpty(pkOldValue)) {
                            Ext.Msg.alert('提示', '第' + (rowIndex + 1) + '行主键[' + field.realName + ']不能为空！');
                            return;
                        }
                        whereStr = whereStr + '`' + field.realName.replaceAll("`" , "``") + "`=" + getFieldValueStr(pkOldValue, field.dataType);
                    }
                });
                if (sql != '') {
                    sql = 'update ' + tableName + ' set ' + sql + ' where ' + whereStr + ';';
                    allSql.push({rowIndex:rowIndex, type:'U', sql:sql});
                }
            }
        });
        return allSql;
    }
};

function showEditDataSql(result_index) {
    var grid = Ext.getCmp('result_' + result_index);
    var tableName = "`" + grid.editDbName + "`.`" + grid.editTableName.replaceAll("`" , "") + "`";
    var deleteSql = update_sql_fun.deleteSQL(tableName , grid);
    var insertSql = update_sql_fun.insertSQL(tableName , grid);
    var updateSql = update_sql_fun.updateSQL(tableName , grid);
    var allSql = new Array();
    allSql = allSql.concat(deleteSql, insertSql, updateSql);
    if (allSql.length == 0) {
        return Ext.MessageBox.alert('提示', '没有数据被修改！');
    }
    var allSqlText = new Array();
    for (var i = 0; i < allSql.length; i++) {
        allSqlText.push(allSql[i].sql);
    }
    var title = '本次操作明细：';
    if (deleteSql.length > 0) {
        title = title + 'delete:' + deleteSql.length + '条；'
    }
    if (insertSql.length > 0) {
        title = title + 'insert:' + insertSql.length + '条；'
    }
    if (updateSql.length > 0) {
        title = title + 'update:' + updateSql.length + '条；'
    }
    var win = Ext.create('Ext.window.Window', {
        title:title + '以下是提交执行的SQL，请确认',
        id:'win_change_sql',
        height:300,
        width:800,
        modal:true,
        maximizable:true,
        layout:'fit',
        items:{  // Let's put an empty grid in just to illustrate fit layout
            xtype:'codemirror',
            readOnly:true,
            value:allSqlText.join("\n")
        },
        buttonAlign:'center',
        buttons:[
            {text:'确定', handler:function () {
                postChange(allSql , grid , win);
            }},
            {text:'取消', handler:function () {
                win.close();
            }}
        ]
    }).show()
}
function postChange(allSql,grid,win) {
    Ext.getBody().mask("正在提交，请稍候......");
    var jsonAllSql = Ext.encode(allSql);
    var paramsValue;
    if(isLocal=='isLocal'){
    	paramsValue={dbName:nowDBName,"dataId":dataBase_id,"baseType":base_type,"dataSourceId":dataSource_id,"dataSource":data_source,"sql":jsonAllSql,isLocal:isLocal}
    }else{
    	paramsValue={dbName:nowDBName,"dataId":dataBase_id,"baseType":base_type,"dataSourceId":dataSource_id,"dataSource":data_source,"sql":jsonAllSql}
    }
    
    ajax({
        url:getRoot() + '/websql/postChange',
        params:paramsValue,
        method:'POST',
        timeout:600000,
        success:function (response, options) {
            Ext.getBody().unmask();
            var rs = jsonDecode(response.responseText);
            var root = rs.root;
            if(isLocal=='isLocal'){
            	if (rs.failure) {
                    Ext.MessageBox.alert('执行出错', root);
                }else {
                    var disableEdit = false;
                    if(root.hasError) {
                        var msg = "" , baseMsg = "执行SQL语句报错：<br/>" + root.errorSQL + "<br/><br/>错误原因：<br/>" + root.errorMsg;
                        if(root.successCount) {
                            msg = "<span style='font-weight: bold;color: red;'>【注意】</span>：SQL已有部分（" + root.successCount + "条）执行成功，该表格数据需[重新查询]后才可以继续[编辑数据]，请确认是否重新查询数据？";
                            disableEdit = true;
                            win.close();
                            Ext.Msg.confirm('错误提示' , baseMsg + "<br/><br/>" + msg , function(v) {
                                if(v == 'yes') {
                                    getPageResult(grid.result_index);
                                }else {
                                    hasSuccessRowCallback(grid,root,disableEdit,win);
                                }
                            });
                        }else {
                            Ext.Msg.alert('错误提示' , baseMsg);
                        }
                    }
                    if(!root.hasError) {
                        hasSuccessRowCallback(grid,root,disableEdit,win);
                    }
                }
            }else{
            	if(rs.success){
            		hasSuccessRowCallback(grid,root,disableEdit,win);
            	}else{
            		if(rs.failure){
                		$.feedbackMessage({
                            type: 'success',
                            message: rs.root,
                            showTime:6000
                        });
                	}else{
                		$.feedbackMessage({
                            type: 'danger',
                            message: rs.root,
                            showTime:8000
                        });
                	}
            	}
            }
        },
        failure:function (response, options) {
            Ext.getBody().unmask();
            Ext.MessageBox.alert('失败', '执行出错，通常是SQL响应时间太长！');
        }
    });
}
function hasSuccessRowCallback(grid,root,disableEdit,win) {
    var records = grid.getStore().getNewRecords();
    Ext.each(root.lastInsertIds , function(row) {
        var record = grid.getStore().getAt(row.rowIndex);
        if (record.raw.__new == 1) {
            record.raw.__new = 0;
        }
        var fields = grid.store.model.getFields();
        for (var j = 0; j < fields.length; j++) {
            if (fields[j].autoIncrement && !record.get(fields[j].name)) {
                record.set(fields[j].name, row.lastInsertId);
                break;
            }
        }
    });
    if(disableEdit) {
        edit_option_fun.disableGridEdit(grid.result_index);
    }else {
        grid.store.commitChanges();
    }
    win.close();
}
function formatSql() {
    var sql = getSql();
    var result = formatsql(sql);
    if(Ext.getCmp("tx_sql").editor.getSelection()) {
    	var cursorBegin = Ext.getCmp("tx_sql").editor.getCursor(true);
    	var cursorEnd = Ext.getCmp("tx_sql").editor.getCursor(false);
    	var resultSplit = result.split("\n");
    	var splitLength = resultSplit.length
    	var newCursorEnd =  CodeMirror.Pos(cursorBegin.line + splitLength - 1, resultSplit[splitLength - 1].length);
        Ext.getCmp("tx_sql").editor.replaceSelection(result);
        Ext.getCmp("tx_sql").editor.setSelection(cursorBegin, newCursorEnd);
    }else {
        Ext.getCmp("tx_sql").setValue(result);
    }
}

var showSqlPlan = function() {
	var sqlText = Ext.String.trim(getSql());
    if (sqlText == "") {
        Ext.MessageBox.alert('提示', '请输入要查看执行计划的SQL！');
        return;
    }
    
    var _explain_tab = new Ext.tab.Panel({
        region:'center',
        tabPosition:'top',
        activeTab:0,
        id:'explain_plan'
    });
    
    Ext.getBody().mask('正在拆分SQL语句...');
    ajax({
    	url:getRoot() + '/websql/splitSQL',
        params:{sqlText:sqlText},
        success:function(resp) {
            Ext.getBody().unmask();
            var json = jsonDecode(resp.responseText);
            if(json.success) {
                var data = json.root;
                var sqlArray  = data.sqlList;
                var timeDelay = data.timeDelay;
                for(var _tt =0;_tt<sqlArray.length;_tt++){
                	 _explain_tab.add(explain_one_sql(sqlArray[_tt],_tt));
                	 _explain_tab.setActiveTab(0);
                }
            }else {
                Ext.Msg.alert('提示' , json.root);
            }
        },
        failure:function(resp) {
            Ext.getBody().unmask();
            Ext.Msg.alert('提示' , resp.responseText);
        }
    });
    
    
    var explain_one_sql = function(_one_sql,_index){
    	if(_one_sql){
            _one_sql=_one_sql;
    	}

    	 var _storeSqlPlan = Ext.create('Ext.data.Store', {
    	        model:'ModelSqlPlan',
    	        pageSize:50,
    	        data:[],
    	        proxy:{
    	            type:'ajax',
    	            url:getRoot() + '/websql/getSqlPlan?dataId='+dataBase_id+'&baseType='+base_type+'&dataSourceId='+dataSource_id+'&dataSource='+data_source+'&isLocal='+isLocal,
    	            reader:{
    	                type:'json',
    	                root:'root'
    	            }
    	        }
    	    });
    	    var getSqlPlan = function() {
    	        if (_one_sql) {
    	            _storeSqlPlan.load({
    	                params:{
    	                    panelKey:getPaneKey(), dbName:nowDBName, sql:_one_sql
    	                }
    	            });
    	        }
    	    };
    	    getSqlPlan();
    	    var _gridSqlPlan = Ext.create('Ext.grid.Panel', {
    	        store:_storeSqlPlan,
    	        region:'center',
    	        id:'one_sql_explain_' + _index,
    	        title:'执行计划' + (_index + 1),
    	        tabConfig:{
    	            tooltip:"SQL:" + _one_sql
    	        },
    	        deferRowRender:false,
    	        sortableColumns:false,
    	        viewConfig:{ stripeRows:true, enableTextSelection:true},
    	        columns:[
    	            {text:"ID", dataIndex:"id", width:40},
    	            {text:"SELECT_TYPE", dataIndex:"select_type", width:120},
    	            {text:"TABLE", dataIndex:"table", width:150},
    	            {text:"TYPE", dataIndex:"type", width:60},
    	            {text:"POSSIBLE_KEYS", dataIndex:"possible_keys", width:200},
    	            {text:"KEY", dataIndex:"key", width:150},
    	            {text:"KEY_LEN", dataIndex:"key_len", width:80},
    	            {text:"REF", dataIndex:"ref", width:100},
    	            {text:"ROWS", dataIndex:"rows", align:'right', width:100},
    	            {text:"EXTRA", dataIndex:"extra", width:300}
    	        ]
    	    });
    	    return _gridSqlPlan;
    }
    
    var win = new IDB.Window({
        title:'执行计划',
        items:[_explain_tab],
        width:964,
        height:420,
        maximizable:true,
        closable:true,
        buttons:[]
    });
    
    win.show();
};
var localStoredSQL = null ,localStoredSQLKey = null;
var initLocalStoredSQL = function() {
    if(other_params) {
        other_params = jsonDecode(other_params);
        var key = localStoredSQLKey = other_params['temp_store_sql_key'];
        localStoredSQL = SimpleStorageUtils.get(key);
        window.onbeforeunload = function(e) {
            var nowValue = SimpleStorageUtils.get(key);
            if(nowValue || nowValue === "") {
                SimpleStorageUtils.set(key , getFullSqlText());
            }
        };
    }
};


function initQuery() {
    initLocalStoredSQL();
    if(localStoredSQL) {
        Ext.getCmp('tx_sql').setValue(localStoredSQL);
    }else if (operation == 'query' && objectName) {
    	var sql;
    	if(_DB_TYPE.toLowerCase() == 'oracle'){
    		sql = 'SELECT * FROM ' + nowDBName.replace("`","") + '.' + objectName.replace("`","") + " " + ";";
    	}else if(_DB_TYPE.toLowerCase() == 'drds'){
    		sql = 'SELECT * FROM ' + nowDBName + '.' + objectName + ";";
    	}else{
    		sql = 'SELECT * FROM `' + nowDBName.replace("`","``") + '`.`' + objectName.replace("`","``") + "`" +  ";";
    	}
        Ext.getCmp('tx_sql').setValue(sql);
        executeSQL();
    }
}
function getInitWhereCondition() {
    if(v_primaryKeys.length > 0) {
        var orderSQL = " ORDER BY ";
        Ext.each(v_primaryKeys , function(row) {
        	if(_DB_TYPE.toLowerCase() == 'oracle' || _DB_TYPE.toLowerCase() == 'drds'){
        		orderSQL += " " + row.replace("`","") + " " + " DESC ,";
        	}else{
        		orderSQL += "`" + row.replace("`","``") + "`" + " DESC ,";
        	}
            
        });
        return orderSQL.substring(0 , orderSQL.length - 1);
    }
    return "";
}


// Cancel功能

var isCancel = false;

var cancelWindow = new Ext.Window({
    width:500,
    height:200,
    layout:'absolute',
    title:'请等待',
    overflowY : 'scroll',
    plain:true,
    bodyStyle:'padding:5px;',
    buttonAlign:'center',
    items:[
        {
            x:20,
            y:20,
            xtype:'label',
            text:'SQL正在执行中......'
        }
    ],
    modal:true,
    closable:false,
    closeAction:'hide',
    buttons:[
        {
            text:'取消执行',
            handler:function () {
            	isCancel = true;
            	cancelWindow.hide();
                cancel();
            }
        }
    ]
});
function cancel() {
    Ext.Ajax.request({
        url:baseUrl + 'cancel.do',
        waitMsg:"请等待!",
        params:{
            event:"cancel",
            panelKey:getPaneKey(), dbName:nowDBName
        }
    });
}





/**************/

var fileTypeArray2 = [
    {data:'CSV' , label:'CSV'},
    {data:'SQL_Insert' , label:'SQL_Insert'}
];
var fileCharsetTypeArray = [
    {data:'utf8'},
    {data:'gbk'}
];
var rowsLimitArray = [
    {data:'10000' , label:'1万'},
    {data:'50000' , label:'5万'},
    {data:'100000' , label:'10万'},
    {data:'200000' , label:'20万'},
    {data:'500000' , label:'50万'},
    {data:'1000000' , label:'100万'},
    {data:'2000000' , label:'200万'},
    {data:'5000000' , label:'500万'}
];
var submitNewSQLJob = function(params) {
    var advanceWindow = createAdvanceWindow();
    params['exportMode'] = "sql";
    params['exportMethod'] = 'data';
    Ext.apply(params , advanceWindow.getAdvanceValues());
    advanceWindow.close();
    Ext.getBody().mask('正在提交任务，请等待....');
    ajax({
        url:'/data/export/saveExportJobBySqlWindow.do',
        params:params,
        success:function(resp) {
            Ext.getBody().unmask();
            var json = jsonDecode(resp.responseText);
            if(json.success) {
                showMonitor(json.root);
            }else {
                Ext.Msg.alert('错误提示' , json.root);
            }
        },
        failure:function() {
            Ext.getBody().unmask();
        }
    });
};
  var addNewSQLJob = function(dbName,sql) {
    var form = new IDB.FormPanel({
        region:'center',
        layout:'column',
        defaults:{margin: '2 2 2 0',width:500,columnWidth:1,labelWidth:100},
        items:[
            {
                columnWidth:.5,
                width:230,
                fieldLabel:'文件类型',
                editable:false,
                blankText:'文件类型不能为空',
                xtype:'combo',
                name:'fileType',
                triggerAction:'all',
                displayField:'label',
                valueField:'data',
                queryMode:'local',
                forceSelection:true,
                typeAhead:true,
                value:'CSV',
                store:new Ext.data.Store({
                    fields:['data' , 'label'],
                    data:fileTypeArray2
                })
            },{
                columnWidth:.5,
                fieldLabel:'文件字符集',
                editable:false,
                blankText:'字符集选项不能为空',
                xtype:'combo',
                name:'fileCharset',
                triggerAction:'all',
                displayField:'data',
                valueField:'data',
                queryMode:'local',
                value:'gbk',
                forceSelection:true,
                typeAhead:true,
                store:new Ext.data.Store({
                    fields:['data'],
                    data:fileCharsetTypeArray
                })
            },
            {
                xtype:'checkboxgroup',
                fieldLabel:'选项',
                id:'check_option',
                columns:1,
                items:[
                    {
                        name:'compressInsert',
                        inputValue:'Y',
                        hidden:true,
                        checked:true,
                        boxLabel:'insert语句合并（以5M为单位将多个insert语句进行合并）'
                    },
                    {
                        name:'enableCsvTitleRow',
                        inputValue:'Y',
                        checked:true,
                        boxLabel:'包含属性行（选中此项CSV第1行为属性名称，否则第1行为数据）'
                    }
                ]
            },
            {
                fieldLabel:'结果集行数限制',
                editable:false,
                xtype:'combo',
                name:'tableRowsLimit',
                triggerAction:'all',
                displayField:'label',
                valueField:'data',
                queryMode:'local',
                value:'200000',
                forceSelection:true,
                typeAhead:true,
                store:new Ext.data.Store({
                    fields:['data' , 'label'],
                    data:rowsLimitArray
                })
            },
            {
                fieldLabel:'数据库',
                name:'dbName',
                blankText:'数据库选项不能为空',
                readOnly:true,
                value:dbName
            },
            {
                fieldLabel:'执行SQL',
                xtype:'textarea',
                height:90,
                maxLength:20000,
                emptyText:'请在这里输入1条Select语句....',
                maxLengthText:'SQL请不要超过20000个字符',
                minLength:8,
                minLengthText:'SQL语句太短',
                name:'sql',
                value:sql,
                allowBlank:false,
                blankText:'SQL语句不能为空'
            },
            {
                fieldLabel:'描述',
                xtype:'textarea',
                height:60,
                maxLength:1024,
                maxLengthText:'请不要超过1024个字符',
                name:'createDesc',
                allowBlank:true
            }
        ]
    });
    var fileTypeField = form.getForm().findField('fileType');
    var setExportCreateScript = function() {
        if(fileTypeField.getValue() == 'SQL_Insert') {
            form.getForm().findField('compressInsert').show();
            form.getForm().findField('enableCsvTitleRow').hide();
        }else {
            form.getForm().findField('compressInsert').hide();
            form.getForm().findField('enableCsvTitleRow').show();
        }
    };
    var submitTO = function() {
        if(form.isValid()) {
            var params = form.getValues();
            params['exportMode'] = "sql";
            params['exportMethod'] = 'data';
            Ext.apply(params , advanceWindow.getAdvanceValues());
            win.getEl().mask('正在提交任务，请等待....');
            ajax({
                url:'/data/export/saveExportJob.do',
                params:params,
                success:function(resp) {
                    win.getEl().unmask();
                    var json = jsonDecode(resp.responseText);
                    if(json.success) {
                        showMonitor(json.root);
                        win.close();
                    }else {
                        Ext.Msg.alert('错误提示' , json.root);
                    }
                },
                failure:function() {
                    win.getEl().unmask();
                }
            });
        }
    };
    fileTypeField.on('select' , setExportCreateScript);
    var win = new IDB.Window({
        title:'新增SQL导出任务',
        width:850,
        height:420,
        closable:true,
        layout:'fit',
        items:[form],
        buttons:[{
            text:'高级选项',handler:function() {
                advanceWindow.show();
            }
        },{
            text:'确定',handler:submitTO
        },{
            text:'关闭',handler:function() {
                win.close();
            }
        }]
    });
    var advanceWindow = createAdvanceWindow();
    win.on('beforedestroy' , function() {
        advanceWindow.close();
    });
};
var createAdvanceWindow = function() {
    var form = new IDB.FormPanel({
        defaults:{
            bodyPadding:5,
            padding:'0 5 0 5',
            xtype:'fieldset',
            width:520,
            defaults:{
                autoFitErrors:false,//自动调整错误提示时候的宽度
                labelSeparator:' : ',
                labelWidth:80,
                width:500,
                labelAlign:'right',
                xtype:'textfield'
            }
        },
        items:[
            {
                title:'数据选项',
                items:[
                    {xtype:'checkboxfield',name:'exportBlob',inputValue:'Y',hiddenLabel:true,checked:false,boxLabel:'导出TINYBLOB、BLOB、MEDIUMBLOB、LONGBLOB类型（输出格式为16进制）'},
                    {xtype:'checkboxfield',name:'exportBinary',inputValue:'Y',hiddenLabel:true,checked:true,boxLabel:'导出BINARY、VARBINARY类型（输出格式为16进制）'},
                    {xtype:'checkboxfield',name:'exportClob',inputValue:'Y',hiddenLabel:true,checked:true,boxLabel:'导出TINYTEXT、TEXT、MEDIUMTEXT、LONGTEXT类型'}
                ]
            }
        ]
    });
    var win = new Ext.window.Window({
        height:220 , width:600 , title:'高级选项',
        modal:true,layout:'fit',closable:false,buttonAlign:'center',items:[form],
        buttons:[{
            text:'确定',handler:function() {
                win.hide();
            }
        }],
        getAdvanceValues:function() {
            return form.getValues();
        }
    });
    return win;
};
var showMonitor = function(id) {
    ajax({
        url:'/data/export/monitorExportJob.do?id='+id + "&firstTime=Y",
        success:function(resp) {
            var json = jsonDecode(resp.responseText);
            if(json.success) {
                showMonitorDoing(json.root , id);
            }else {
                Ext.Msg.alert('提示' , json.root);
            }
        }
    });
};
var showMonitorDoing = function(json , id) {
    if(json['exportStatus'] == 'END' && json['exportMode'] != 'sql') {
        return showDetail(id);
    }
    var use = getProcess(json);
    var sql = json['sql'];
    var processBar = new Ext.ProgressBar({
        width:500,height:45,text:'当前进度：' + use + "%",paddingTop:5,region:'north' , margin:'3 12 3 12'
    });
    processBar.updateProgress(parseFloat(use)/100 , '当前进度：' + use + "%&nbsp;&nbsp;&nbsp;&nbsp;已导出总行数：" + json['nowRows'] , true);
    var win = new IDB.Window({
        title:'任务进度跟踪(每2s刷新一次进度)',
        layout:'border',
        width:680,
        height:450,
        items:[{
            region:'north',height:30,border:false,layout:'fit',items:[processBar],id:'processBarArea'
        },{
            html:'详情',region:'center',layout:'fit',border:false,baseCls:'log_content',id:'oneTableLog',xtype:'container'
        }],
        buttons:[{
            text:'关闭',handler:function() {
                win.close();
            }
        },{
            hidden:true,
            id:'monitor_download_file',
            text:'下载文件',handler:function() {
                downloadAllFile(id);
            }
        }]
    });
    var nowLogContentDom = Ext.getCmp('oneTableLog').el.dom;
    nowLogContentDom.innerHTML = "<pre>" + getMonitorBaseInfoByRow(json , new Date()) + (json['log'] || '') + "</pre>";
    var task = {
        interval:2000,
        run:function() {
            var date = new Date();
            ajax({
                url:'/data/export/monitorExportJob.do?id='+id,
                success:function(resp) {
                    var json = jsonDecode(resp.responseText);
                    if(json.success) {
                        json = json.root;
                        json['sql'] = sql;
                        var use = getProcess(json);
                        processBar.updateProgress(parseFloat(use)/100 , '当前进度：' + use + "%<br/>已导出总行数：" + json['nowRows'] , true);
                        nowLogContentDom.innerHTML = "<pre>" + getMonitorBaseInfoByRow(json , new Date()) + (json['log'] || '') + "</pre>";
                        nowLogContentDom.scrollTop = nowLogContentDom.scrollHeight;
                        if(json['exportStatus'] == 'END') {
                            Ext.TaskManager.stop(task);
                            win.setTitle("详情");
                            Ext.getCmp('monitor_download_file').show();
                            downloadAllFile(id);
                        }else if(json['exportStatus'] == 'ERROR') {
                            Ext.TaskManager.stop(task);
                            win.setTitle("查看错误信息");
                            Ext.getCmp('processBarArea').hide();
                        }
                    }else {
                        Ext.Msg.alert('提示' , json.root);
                    }
                }
            });
        }
    };
    if(json['exportStatus'] != 'ERROR') {
        Ext.TaskManager.start(task);
        win.on('beforedestroy' , function() {
            Ext.TaskManager.stop(task);
        });
    }else {
        win.setTitle("查看错误信息");
        Ext.getCmp('processBarArea').hide();
    }
};
var getMonitorBaseInfoByRow = function(row , date) {
    if(row['exportMode'] == 'sql') {
        return '======================================================================\n' +
            '     当前状态：' + Ext.util.Format.htmlDecode(row['statusName']) +  "\n" +
            '     刷新时间：' + Ext.util.Format.date(date , 'Y-m-d H:i:s') + '\n' +
            '     ' + Ext.util.Format.htmlDecode(row['nowLog'] || '等待执行....') +  "\n" +
            '     SQL语句：\n' +
            '     ' + String(row['sql']).replaceAll("\n" , "\n     ") + '\n' +
            '======================================================================\n';
    }
    return '======================================================================\n' +
        '     当前状态：' + Ext.util.Format.htmlDecode(row['statusName']) +  "\n" +
        '     已导出表：' + Ext.util.Format.htmlDecode(row['exportedTabs'])  + " / " + Ext.util.Format.htmlDecode(row['exportTabNum']) +  "\n" +
        '     刷新时间：' + Ext.util.Format.date(date , 'Y-m-d H:i:s') + '\n' +
        '     ' + Ext.util.Format.htmlDecode(row['nowLog'] || '等待执行....') +  "\n" +
        '======================================================================\n';
};
var getProcess = function(data) {
    var use = 0;
    if(data['exportStatus'] == 'END') {
        return 100;
    }
    if(data['preRows'] && data['exportStatus'] != 'END') {
        use = ((parseFloat(data['nowRows']) / parseInt(data['preRows'])) * 100).toFixed(0);
        if(use >= 100) {
            use = 99;
        }
    }else {
        use = ((parseFloat(data['completeSize']) / parseInt(data['exportTabSize'])) * 100).toFixed(0);
    }
    return use;
};
var downloadAllFile = function(id) {
    downLoadFileByURL("/mysql/data/export/downLoadAllFile.do?id=" + id + "&token=" + getUserToken());
};


